import com.sun.source.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/*
 * @author zzr
 * @date: 2025/10/17  20:27
 * @description: 对二叉树进行层序遍历
 */
public class Demo26 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //    public void levelOrder(TreeNode root) {
//        if (root == null) return;
//
//        Queue<TreeNode> queue = new LinkedList<>();
//        TreeNode cur = null;
//
//        queue.offer(root);
//        while (!queue.isEmpty()) {
//            cur = queue.poll();
//            System.out.println(cur.val + " ");
//
//            if (cur.left != null) {
//                queue.offer(cur.left);
//            }
//            if (cur.right != null) {
//                queue.offer(cur.right);
//            }
//        }
//    }
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> ret = new ArrayList<>();

        if (root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {

            // 先要求一下队列的长度
            int size = queue.size();

            List<Integer> tmp = new ArrayList<>();
            while (size != 0) {
                // 出队 size 此，就相当于把这一层的节点都出队
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                size--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}
